package com.ruitu.mall_98_1.product.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.BaseActivity;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.widget.MyPopWindow;
import com.beanu.arad.widget.dialog.AlertDialogFragment;
import com.ruitu.mall_98_1.R;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.mine.Address;
import com.ruitu.router_module.bean.order.MyAdvanceOrder;
import com.ruitu.router_module.bean.product.Product;
import com.ruitu.router_module.bean.product.Sku;
import com.ruitu.router_module.bean.product.SpecInfo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

//预订
public class BookProActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_title, tv_select_addr, tv_ok, tv_spec;//标题,选择地址,确定,选择规格
    private EditText et_name, et_phone, et_spec, et_num, et_txt;//姓名,手机号,规格,数量,其他备注
    private Toolbar toolbar;

    private Product product;
    private Address currAddr;//当前选择的地址
    private String addrStr = "";//详细地址

    private MyAdvanceOrder preOrder;//修改订单时传过来的对象

    String userName = "";
    String userPhone = "";
    String goodsSpec = "";
    int goodsNum = 0;
    String intro = "";

    String status = "0";//0 提交 1 修改
    String goodsId = "";
    String addressId = "";
    String reserveId = "";
    String accountId = "";

    private List<Sku> skuList = new ArrayList<>();//套餐形式的规格

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_pro);
        tv_title = findViewById(R.id.tv_title);
        tv_select_addr = findViewById(R.id.tv_select_addr);
        tv_ok = findViewById(R.id.tv_ok);
        et_name = findViewById(R.id.et_name);
        et_phone = findViewById(R.id.et_phone);
        et_spec = findViewById(R.id.et_spec);
        tv_spec = findViewById(R.id.tv_spec);
        et_num = findViewById(R.id.et_num);
        et_txt = findViewById(R.id.et_txt);
        toolbar = findViewById(R.id.toolbar);
        if (null != toolbar) {
            toolbar.setNavigationIcon(com.beanu.arad.R.mipmap.arad_ic_back_normal);
            toolbar.setNavigationOnClickListener(this);
            toolbar.setTitle("");
        }

        accountId = AppHolder.instance().getUser().getAccountId();

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            preOrder = (MyAdvanceOrder) bundle.getSerializable("preOrder");
            if (null != preOrder) {//说明是要修改订单
                tv_title.setText("修改预订");
                status = "1";
                goodsId = preOrder.getGoodsId();
                goodsNum = preOrder.getGoodsNum();
                goodsSpec = preOrder.getGoodsSpec();
                accountId = preOrder.getAccountId();
                userName = preOrder.getUserName();
                userPhone = preOrder.getUserPhone();
                intro = preOrder.getIntro();
                addressId = preOrder.getAddressId();
                reserveId = preOrder.getId();//预订单id 修改的时候需要传

                et_name.setText(userName);
                et_phone.setText(userPhone);
                et_spec.setText(goodsSpec);
                tv_spec.setText(goodsSpec);
                et_num.setText(goodsNum + "");

                try {
                    currAddr = preOrder.getAddress();
                    addrStr = currAddr.getProvince() + currAddr.getCity()
                            + currAddr.getCounty() + currAddr.getAddress();
                    tv_select_addr.setText(addrStr);
                } catch (Exception e) {
                    tv_select_addr.setText("");
                }

                et_txt.setText(preOrder.getIntro());
            } else {//说明是提交订单
                reqAddr();//获取地址列表,如果有,取第一条默认地址设置收货人
                tv_title.setText("商品预订");
                product = (Product) bundle.getSerializable("product");//从商品详情直接预订
                goodsId = product.getGoodId();
                if (CommonUtils.isLogin()) {
                    et_name.setText(AppHolder.instance().getUser().getNickName());
                    et_phone.setText(AppHolder.instance().getUser().getPhone());
                }
            }
            showProgress(true);
            reqProSpecData();//请求规格列表
        } else {
            tv_title.setText("商品预订");
        }

        setListeners();
        Arad.bus.register(this);
    }

    private void reqProSpecData() {
        APIRetrofit.getDefault().reqProSpec(goodsId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<SpecInfo>>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        showProgress(false);
                    }

                    @Override
                    public void onNext(BaseResult<SpecInfo> listResult) {
                        showProgress(false);
                        if (listResult.isSuccess()) {
                            SpecInfo specInfo = listResult.getData();
                            skuList = specInfo.getSkuList();
                            if (null != skuList && skuList.size() > 0) {//说明有规格数据
                                tv_spec.setVisibility(View.VISIBLE);
                                et_spec.setVisibility(View.GONE);
                            }
                        } else {
                            ToastUtils.showShort(listResult.getMsg());
                        }
                    }
                });
    }

    private void reqAddr() {
        if (CommonUtils.isLogin()) {
            APIRetrofit.getDefault().reqAddr(AppHolder.instance().getUser().getAccountId())
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SubscriberImpl<BaseResult<List<Address>>>() {
                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onNext(BaseResult<List<Address>> listResult) {
                            List<Address> addressList = listResult.getData();
                            if (null != addressList && addressList.size() > 0) {
                                currAddr = addressList.get(0);
                                addressId = currAddr.getId();
                                et_name.setText(currAddr.getName());
                                et_phone.setText(currAddr.getPhone());
                                addrStr = currAddr.getProvince() + currAddr.getCity()
                                        + currAddr.getCounty() + currAddr.getAddress();
                                tv_select_addr.setText(addrStr);
                            }
                        }
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(EventModel e) {
        if (e.getEventCode() == 18111600) {//选择了收货地址
            currAddr = (Address) e.getEventObj();
            if (null != currAddr) {
                addrStr = currAddr.getProvince() + currAddr.getCity()
                        + currAddr.getCounty() + currAddr.getAddress();
                tv_select_addr.setText(addrStr);
                et_name.setText(currAddr.getName());
                et_phone.setText(currAddr.getPhone());
                addressId = currAddr.getId();
            }
        }
    }

    private void setListeners() {
        tv_select_addr.setOnClickListener(this);
        tv_ok.setOnClickListener(this);
        tv_spec.setOnClickListener(this);
    }

    private View popViewArea;
    private MyPopWindow popA1;

    protected void initPopupWindow() {
        popViewArea = View.inflate(this, R.layout.pop_spec_list, null);
        popA1 = new MyPopWindow(popViewArea, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        popA1.setFocusable(true);
//        popA1.setBackgroundDrawable(new ColorDrawable(66000000));
        popA1.setBackgroundDrawable(new ColorDrawable(00000000));
        popA1.setOutsideTouchable(true);

        RecyclerView rcv_list = popViewArea.findViewById(R.id.rcv_list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rcv_list.setLayoutManager(manager);
        final SpecListAdapter adapter = new SpecListAdapter(this);
        rcv_list.setAdapter(adapter);
        adapter.setDataList(skuList);
        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                tv_spec.setText(skuList.get(position).getName());
                et_spec.setText(skuList.get(position).getName());
                popA1.dismiss();
            }
        });
        popViewArea.findViewById(R.id.pop_bg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popA1.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == -1) {//点击的是toolbar左上角的按钮
            UIUtils.hideInput(this, et_txt.getWindowToken());
            onBackPressed();
        }
        if (v == tv_spec) {//选择规格
            initPopupWindow();
//            popA1.showAsDropDown(tv_spec, SizeUtils.dp2px(20),SizeUtils.dp2px(20), Gravity.TOP | Gravity.CENTER_HORIZONTAL);
            popA1.showAsDropDown(tv_spec);
        }
        if (v == tv_select_addr) {
            if (CommonUtils.isLoginToActivity(this)) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putString("from", "from");
                    A_Rutils.startActivity(this, "com.ruitu.mall_98_2.mine.AddressListActivity", bundle);
                } catch (Exception e) {
                }
            } else {
                ToastUtils.showShort("请先登录");
            }
        }
        if (v == tv_ok) {
            if (UIUtils.isEtEmpty(et_name)) {
                ToastUtils.showShort("请输入姓名");
                return;
            }
            if (UIUtils.isEtEmpty(et_phone)) {
                ToastUtils.showShort("请输入手机号");
                return;
            }
            if (UIUtils.isEtEmpty(et_spec)) {
                ToastUtils.showShort("请输入规格");
                return;
            }
            if (UIUtils.isEtEmpty(et_num)) {
                ToastUtils.showShort("请输入数量");
                return;
            }
            if (null == currAddr || TextUtils.isEmpty(addressId)) {
                ToastUtils.showShort("请选择地址");
                return;
            }
            if (UIUtils.isEtEmpty(et_txt)) {
                ToastUtils.showShort("请输入留言或者备注信息");
                return;
            }

            userName = et_name.getText().toString().trim();
            userPhone = et_phone.getText().toString().trim();
            goodsSpec = et_spec.getText().toString().trim();
            goodsNum = Integer.parseInt(et_num.getText().toString().trim());
            intro = et_txt.getText().toString().trim();
            String orderInfo = "姓名：" + userName + "\n"
                    + "电话：" + userPhone + "\n"
                    + "规格：" + goodsSpec + "\n"
                    + "数量：" + goodsNum + "\n"
                    + "地址：" + addrStr + "\n"
                    + "备注：" + intro;
            UIUtils.showAlertDialog(getSupportFragmentManager(), "请确认订单信息", orderInfo
                    , "提交", "修改",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            reqSaveBook();
                        }
                    }, null);
        }
    }

    private void reqSaveBook() {//提交预订申请
        showProgressWithText(true, "提交中...");
        APIRetrofit.getDefault().reqSaveBook(status, goodsId, goodsNum, goodsSpec, accountId
                , userName, userPhone, intro, addressId, reserveId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        showProgress(false);
                        ToastUtils.showLong("提交失败,请重试");
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        showProgress(false);
                        if (baseResult.isSuccess()) {
                        } else {
                        }
                        AlertDialogFragment dialog = UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", baseResult.getMsg()
                                , "好的", "我知道了", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                }, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                });
                        dialog.setCancelable(false);
                    }
                });
    }

    private class SpecListAdapter extends ListBaseAdapter<Sku> {

        public SpecListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.pop_item_search_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            tv_name.setText(mDataList.get(position).getName());
        }
    }
}
